<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #messages {
            border: 1px solid #ccc;
            height: 200px;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1>WebSocket Client</h1>
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="Type a message...">
    <button onclick="sendMessage()">Send</button>

    <script>
        // 创建WebSocket连接
        const ws = new WebSocket('ws://localhost:6234'); // 替换为您的WebSocket服务器地址

        // 处理连接打开事件
        ws.onopen = () => {
            console.log('Connected to WebSocket server');
            document.getElementById('messages').innerHTML += '<p>Connected</p>';
        };

        // 处理接收到的消息
        ws.onmessage = (event) => {
            console.log('Message from server:', event.data);
            document.getElementById('messages').innerHTML += `<p>${event.data}</p>`;
        };

        // 处理连接关闭事件
        ws.onclose = () => {
            console.log('Disconnected from WebSocket server');
            document.getElementById('messages').innerHTML += '<p>Disconnected</p>';
        };

        // 处理连接错误事件
        ws.onerror = (error) => {
            console.error('WebSocket Error:', error);
            document.getElementById('messages').innerHTML += `<p>Error: ${error.message}</p>`;
        };

        // 发送消息函数
        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value;
            if (message.trim() !== '') {
                ws.send(message);
                input.value = '';
            }
        }
    </script>
</body>
</html>